package virtualstock.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import virtualstock.exception.InvalidParameterException;
import virtualstock.exception.PlayerNotFoundException;
import virtualstock.request.GameController;
import virtualstock.util.GameDetails;

/**
 * Servlet implementation class CreateGameServlet
 */
public class CreateGameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private GameController gameController; 
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateGameServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	out.print("in CreateGameServlet");
    	
    	String name = (String) request.getParameter("name");
    	Long creator = new Long((String) request.getParameter("creator"));
    	int maxPlayer = Integer.parseInt((String) request.getParameter("maxplayer"));
    	BigDecimal initialBalance = new BigDecimal((String) request.getParameter("initialbalance"));
    	Date startDate = new Date();
    	
    	try {
    		GameDetails details = new GameDetails(name, creator, maxPlayer, initialBalance, startDate);
    		out.print(details);
    		Long gameID = gameController.createNewGame(details);
    		// !!! there's a problem when creating the game with the creator
    		//Long gameID = gameController.createNewGame(details, creator);
        	details.setGameID(gameID);
		} catch (InvalidParameterException e) {
			out.print("InvalidParameterException");
			e.printStackTrace();
		} catch (PlayerNotFoundException e) {
			out.print("GameNotFoundException");
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("ListGameServlet").forward(request, response);
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
